﻿/// <reference path="_references.js" />
var myUserId;
var currentGameId;

$(document).ready(function () {
    makeMeInactive();

    $("#dialog-gameOver").dialog({
        autoOpen: false
    });

    //Open connection for the hub
    var gameHub = $.connection.snakesGameHub;

    $("#move").click(function () {
        gameHub.server.rollDice(currentGameId, myUserId);
        makeMeInactive();
    });
    //Generate the players and start the game
    gameHub.client.startGame = function (numberOfPlayers, playAgainstComputer) {
        //Hide the chat if playing against the computer

        if (!playAgainstComputer) {
            $("#chat").css('visibility', 'visible');
        }
        generatePlayers(numberOfPlayers);
        //If the user id = 1, it's the user's turn
        if (myUserId == 1) {
            makeMeActive();
        }
    }
    //Let the user know what his player id is
    gameHub.client.sendUserId = function (userId) {
        myUserId = userId;
    }
    //Move the player
    gameHub.client.makeMove = function (playerId, locations, nextPlayerId, diceResult) {
        //Display in the whosTurn div who's turn it is
        var whosTurnDiv = $("#whosTurn");
        whosTurnDiv.html("Spilari: " + nextPlayerId + " á að gera!");
        //Display in the diceResultDiv what result the players got in the dice
        var diceResultDiv = $("#diceResult");

        //If the player got 6 on the dice, it's his turn again
        if (nextPlayerId == playerId) {
            diceResultDiv.html(diceResultDiv.html() + "Spilari " + playerId + " fékk " + diceResult + " á teninginn og gerir aftur.<br />");
        }
        else {
            diceResultDiv.html(diceResultDiv.html() + "Spilari " + playerId + " fékk " + diceResult + " á teninginn.<br />");
        }

        //Makes the dice result box scroll in the right way
        diceResultDiv.scrollTop(diceResultDiv[0].scrollHeight);
        //Animate the pieces
        animatePiece(playerId, nextPlayerId, locations);

        //Function to show the user who won the game
    }
    gameHub.client.sendWinner = function (playerId, diceResult) {
        $("#whosTurn").html("");
        move(playerId, 100);
        makeMeInactive();
        $("#winner").html("<strong>Leikmaður " + playerId + "</strong> fékk " + diceResult + " á tenginginn og er SIGURVEGARI!");
        $("#dialog-gameOver").dialog("open");
    }

    //Shows the chat messages
    gameHub.client.addMessage = function (myUserName, message) {
        var messages = $('#messages');
        messages.html(messages.html() + '<strong>' + myUserName + ":</strong> " + message + "<br />");
        messages.scrollTop(messages[0].scrollHeight);
    }

    //Send message
    $("#broadcast").click(function () {
        if ($('#msg').val() === '') {
            $('#msg').val('').focus();
        }
        else {
            gameHub.server.send($('#msg').val(), currentGameId, myUserId);
            $('#msg').val('').focus();
        }
    });
    $("#broadcast").keyup(function () {
        if (event.which == 13) {
            if ($('#msg').val() === '') {
                $('#msg').val('').focus();
            }
            else {
                gameHub.server.send($('#msg').val(), currentGameId, myUserId);
                $('#msg').val('').focus();
            }
        }
    });

    //Start the connection
    $.connection.hub.start().done(function () {
        //Get group ID from the URL
        var url = document.URL;
        currentGameId = url.substr(url.lastIndexOf("/") + 1);
        //Join the game
        gameHub.server.join(currentGameId);

    }).fail(function () {
        alert("ERROR");
    });
});
//Generate the players
function generatePlayers(count) {
    var players = $("#players");
    for (var i = 1; i <= count; i++) {
        players.append("<span id=\"player" + i + "\" class=\"player\"></span>");
    }
}
//Move the players
function move(player, newLocation) {
    var td = $("#" + newLocation);
    var html = "<span id=\"player" + player + "\" class=\"player\"></span>";
    $("#player" + player).remove();
    td.html(td.html() + html);
}
//makeMeActive and makeMeInactive are to disable/enable the move button(dice)
function makeMeActive() {
    $("#move").removeAttr('disabled');
}

function makeMeInactive() {
    $("#move").attr('disabled', 'disabled');
}

//Animation for the pieces		
function animatePiece(playerId, nextPlayerId, locations) {
    if (locations.length > 0) {
        move(playerId, locations[0]);
        setTimeout(function () {
            animatePiece(playerId, nextPlayerId, locations.slice(1));
        }, 500);
    }
    else {
        //If next player is the player himself, it's his turn		
        if (nextPlayerId == myUserId) {
            makeMeActive();
        }
    }
}